﻿Imports System.Activities
Imports System.Data.SqlClient
Imports System.Activities.Presentation.Metadata
Imports System.ComponentModel
Imports System.Activities.Presentation.PropertyEditing
Imports System.Drawing

Public Class GetDatabaseListActivity
    Inherits MSSQLBaseActivity

    Public Property Condition As InArgument(Of String)

    Public Sub New()
        Me.DisplayName = My.Resources.GetDatabaseListActivityDisplayName
    End Sub

    Protected Overrides Function BeginExecute(context As System.Activities.AsyncCodeActivityContext, callback As System.AsyncCallback, state As Object) As System.IAsyncResult
        Dim condition = context.GetValue(Me.Condition)
        Dim conn = context.GetValue(Me.ConnectionStrings)
        Dim useLog = context.GetValue(Me.OutSQLLog)
        Dim asyncExecute = New asyncExecuteDelegate(AddressOf ExecuteSQL)
        context.UserState = asyncExecute

        Return asyncExecute.BeginInvoke(CreateSQLStrings(condition), conn, True, useLog, callback, state)
    End Function

    Public Overrides Sub Register()
        MyBase.Register()

        Dim build As New AttributeTableBuilder
        'ExecuteApplicationActivity Activity
        build.AddCustomAttributes(GetType(GetDatabaseListActivity),
                                              New ToolboxBitmapAttribute(GetType(GetDatabaseListActivity), "GetDatabaseList.png"))
        build.AddCustomAttributes(GetType(GetDatabaseListActivity), "Condition",
                                      New CategoryAttribute(My.Resources.CategoryDetail),
                                      New DisplayNameAttribute(My.Resources.ConditionDisplay),
                                      New DescriptionAttribute(My.Resources.ConditionDescription))

    End Sub

    Private Function CreateSQLStrings(ByVal condition As String) As String
        Dim sqlBuilder As New System.Text.StringBuilder
        With sqlBuilder
            .Append("SELECT ")
            .Append("  A.NAME, ")
            .Append("  A.CREATE_DATE, ")
            .Append("  A.COMPATIBILITY_LEVEL ")
            .Append("FROM ")
            .Append("  SYS.DATABASES AS A ")
            If condition.Trim <> "" Then
                .Append("WHERE ")
                .Append(condition + " ")
            End If
            .Append(";")
        End With
        Return sqlBuilder.ToString
    End Function

End Class
